/*
 * @Author: CemCode
 * @Date: 2023-04-23 09:07:25
 * @LastEditTime: 2023-12-11 10:14:51
 * @Description: file content
 */
const {
    json,
    isEmpty,
    writeFile,
    radomImgs
} = require("../../utils/index");
const {
    db,
    query
} = require("../../db/index");
const {
    v4: uuidv4
} = require("uuid")
const {
    insertLogInfo
} = require("../../utils/log-tools");
const fs = require("fs");
const path = require("path");

// 获取文章列表
exports.getArticleList = (req, res) => {
    const {
        pageNum,
        pageSize,
        articleTitle,
        startTime,
        isDraft,
        endTime,
        type,
        label
    } = req.query;
    const condition = [
        isEmpty(articleTitle) ? " 1=1 and" : `article_title like '%${articleTitle}%' and `,
        isEmpty(type) ? " 1=1 and" : ` type='${type}' and `,
        isEmpty(label) ? " 1=1 and" : ` label like '%${label}%' and `,
        isEmpty(startTime) || isEmpty(endTime) ? " 1=1 and" : ` (create_time>=${startTime} and create_time<=${endTime}) and `,
        isEmpty(isDraft) ? " 1=1 and" : ` isDraft=${isDraft}`,
        ` status=0 `,
        `order by create_time desc limit ${(pageNum-1)*pageSize},${pageSize}`
    ]
    const sqlStr = `select * from t_article where ${condition.join("")}`;
    const selectAllCount = `select count(*) as count from t_article`;
    console.log(sqlStr);
    let backData = {
        data: [], // 所查询到的数据
        pageNum, // 当前页码
        pageSize, // 每页显示的条数
        total: 0 // 总条数
    };
    query(selectAllCount).then(result => {
        backData.total = result[0].count;
        return query(sqlStr);
    }).then(result => {
        backData.data = result;
        res.send(json("success", 0, backData));
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("sql错误" + err));
    })

}

// 添加文章
exports.addArticle = (req, res) => {
    const body = req.body;
    const obj = {
        id: uuidv4().replace(/-/g, ""),
        article_title: body.articleTitle,
        type: body.type,
        label: body.label,
        path: body.path,
        icon: radomImgs(),
        article_brief: body.articleBrief,
        is_draft: body.isDraft,
        content: body.content,
        create_time: Date.now(),
        modify_time: Date.now()
    }
    let sqlStr = "select id from t_article where article_title=?";
    //先查看是否有相同的标题了
    query(sqlStr, obj.article_title).then(result => {
        if (!isEmpty(result) && result.length > 0) {
            throw new Error("该标题已存在");
        }
        //写入文件内容
        obj.path = path.join(file_config.nowFolderPath,obj.article_title + ".md");
        return writeFile(obj.path, obj.content);
    }).then(() => {
        sqlStr = "insert into t_article (id,icon,article_title,type,label,path,create_time,article_brief,modify_time,is_draft) values(?,?,?,?,?,?,?,?,?,?)";
        return query(sqlStr, [obj.id, obj.icon, obj.article_title, obj.type, obj.label, obj.path, obj.create_time, obj.article_brief, obj.modify_time, obj.is_draft]);
    }).then(() => {
        let dataJson = require("../../configs/server_info.json")
        dataJson.last_submit_article_date = Date.now()
        writeFile(path.join(process.cwd() + "\\configs\\server_info.json"), JSON.stringify(dataJson)).then(result => {}).catch(err => {
            insertLogInfo(0, err)
        })
        res.send(json("新增成功", 0));
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json(err.message));
    });
}

// 修改文章
exports.updateArticle = async function (req, res) {
    const body = req.body;
    const obj = {};
    if (!isEmpty(body.articleTitle)) obj.article_title = body.articleTitle;
    if (!isEmpty(body.type)) obj.type = body.type;
    if (!isEmpty(body.isDraft)) obj.is_draft = body.isDraft;
    if (!isEmpty(body.articleBrief)) obj.article_brief = body.articleBrief;
    // 运行label为空
    obj.label = body.label;
    if (!isEmpty(body.modify_time)) obj.modify_time = Date.now();
    if (!isEmpty(body.status)) obj.status = body.status;
    const {
        id,
        content
    } = body;

    // 先获取数据库的值
    const sql = "select article_title,path from t_article where id=?";
    let data = (await query(sql, id))[0];
    let oldPath = data.path;
    //1. 先判断是否重命
    if (!isEmpty(body.articleTitle) && body.articleTitle !== data.article_title) {
        // 重命名
        let newPath = oldPath.replace(/[^\s\\]*.md$/, body.articleTitle + ".md");
        fs.renameSync(oldPath, newPath);
        oldPath = newPath;
        obj.path = oldPath;
    }
    //2. 判断是否修改内容
    if (!isEmpty(content)) {
        await writeFile(oldPath, content);
    }
    //3. 更新数据库
    let sqlStr = `update t_article set ? where id=?`;
    query(sqlStr, [obj, id]).then(result => {
        if (result.affectedRows === 1) {
            // 记录修改时间
            let dataJson = require("../../configs/server_info.json")
            dataJson.last_submit_article_date = Date.now()
            writeFile(process.cwd(),"configs","server_info.json", JSON.stringify(dataJson)).then(result => {}).catch(err => {
                insertLogInfo(0, err)
            })
            return res.send(json("修改成功", 0));
        }
        res.send(json("修改失败"));
    })
}

// 删除文章
exports.delArticle = (req, res) => {
    const {
        id
    } = req.body;
    const sqlStr = "update t_article set status=1 where id=?"
    query(sqlStr, id).then(result => {
        if (result.affectedRows !== 1) {
            res.send(json("删除失败"));
        } else {
            res.send(json("删除成功", 0));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("sql错误"));
    })
}

// 新增类别
exports.addType = (req, res) => {
    const body = req.body;
    const sqlStr = "insert into t_type (id,type_name,annotation,create_time,modify_time,status) values(?,?,?,?,?,?)";
    const sql_select = "select id from t_type where status=0 and type_name=?";
    query(sql_select, body.typeName).then(result => {
        if (result.length > 0) {
            throw new Error("该类别已存在")
        }
        return query(sqlStr, [uuidv4().replace(/-/g, ""), body.typeName, body.annotation, Date.now(), Date.now(), 0]);
    }).then(result => {
        if (result.affectedRows === 1) {
            res.send(json("新增成功", 0));
        } else {
            res.send(json("新增失败"));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json(err.message));
    })
}

// 修改类别
exports.updateType = (req, res) => {
    const {
        id
    } = req.body;
    const body = req.body;
    const obj = {
        id,
        modify_time: Date.now()
    };
    const sql_update = "update t_type set ? where id=?";
    const sql_select = "select id from t_type where type_name=? and id!=?";
    if (!isEmpty(body.typeName)) obj.type_name = body.typeName;
    if (!isEmpty(body.annotation)) obj.annotation = body.annotation;
    if (!isEmpty(body.status)) obj.status = body.status;

    query(sql_select, [body.typeName,body.id]).then(result => {
        if (result.length > 0) {
            throw new Error("该类别已存在");
        }
        return query(sql_update, [obj, id]);
    }).then(result => {
        if (result.affectedRows === 1) {
            res.send(json("修改成功", 0));
        } else {
            res.send(json("修改失败"));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json(err.message));
    });
}

// 删除类别
exports.delType = (req, res) => {
    const {
        id
    } = req.body;
    const sql_update = "update t_type set status=1 where id=?";
    query(sql_update, id).then(result => {
        if (result.affectedRows === 1) {
            res.send(json("删除成功", 0));
        }else{
            res.send(json("删除失败"));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("sql错误"));
    });
}

// 新增标签
exports.addLabel = (req, res) => {
    const body = req.body;
    const sqlStr = "insert into t_label (id,label_name,belongs_type,annotation,create_time,modify_time,status) values(?,?,?,?,?,?,?)";
    const sql_select = "select id from t_label where status=0 and label_name=?";
    const sql_select_type = "select id from t_type where status=0 and type_name=?";

    query(sql_select, body.labelName).then(result => {
        if (result.length > 0) {
            throw new Error("该标签已存在")
        }
        return query(sql_select_type, body.belongsType);
    }).then(result => {
        if (result.length > 0) {
            return query(sqlStr, [uuidv4().replace(/-/g, ""), body.labelName, body.belongsType, body.annotation, Date.now(), Date.now(), 0]);
        }
        throw new Error("该类型不存在");
    }).then(result => {
        if (result.affectedRows === 1) {
            res.send(json("新增成功", 0));
        } else {
            res.send(json("新增失败"));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json(err.message));
    })
}

// 修改标签
exports.updateLabel = async function (req, res) {
    const {
        id
    } = req.body;
    const body = req.body;
    const obj = {
        id,
        modify_time: Date.now()
    };
    const sql_update = "update t_label set ? where id=?";
    const sql_select = "select id from t_label where label_name=?";
    const sql_select_type = "select id from t_type where status=0 and type_name=?";

    if (!isEmpty(body.labelName)) obj.label_name = body.labelName;
    if (!isEmpty(body.belongsType)) obj.belongs_type = body.belongsType;
    if (!isEmpty(body.annotation)) obj.annotation = body.annotation;
    if (!isEmpty(body.status)) obj.status = body.status;
    if (!isEmpty(obj.belongs_type)) {
        // 检查该类型会不会存在
        const data = await query(sql_select_type, body.belongsType);
        if (data.length === 0) {
            return res.send(json("该类型不存在"));
        }
    }
    query(sql_select, [body.typeName]).then(result => {
        if (result.length > 0) {
            throw new Error("该标签已存在");
        }
        return query(sql_update, [obj, id]);
    }).then(result => {
        if (result.affectedRows === 1) {
            res.send(json("修改成功", 0));
        } else {
            res.send(json("修改失败"));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json(err.message));
    });
}

// 删除标签
exports.delLabel = (req, res) => {
    const {
        id
    } = req.body;
    const sql_update = "update t_label set status=1 where id=?";
    query(sql_update, id).then(result => {
        if (result.affectedRows === 1) {
            res.send(json("删除成功", 0));
        }else{
            res.send(json("删除失败"));
        }
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("sql错误"));
    });
}

// 获取标签列表
exports.getLabelList = (req, res) => {
    const {
        pageNum,
        pageSize,
        labelName,
        belongType,
        status
    } = req.query;
    const condition = [
        isEmpty(labelName) ? " 1=1 and" : `label_name like '%${labelName}%' and `,
        isEmpty(belongType) ? " 1=1 and" : ` belongs_type='${belongType}' and `,
        isEmpty(status) ? " status=0 " : ` status=${status} `,
        `limit ${(pageNum-1)*pageSize},${pageSize}`
    ]
    const sqlStr = `select * from t_label where ${condition.join("")}`;
    const selectAllCount = `select count(*) as count from t_label ${isEmpty(status)?"where status=0":`where status=${status}`}`;
    console.log(sqlStr);
    let backData = {
        data: [], // 所查询到的数据
        pageNum, // 当前页码
        pageSize, // 每页显示的条数
        total: 0 // 总条数
    };
    query(selectAllCount).then(result => {
        backData.total = result[0].count;
        return query(sqlStr);
    }).then(result => {
        backData.data = result;
        res.send(json("success", 0, backData));
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("sql错误" + err));
    })
}

// 获取类型列表
exports.getTypeList = (req, res) => {
    const {
        pageNum,
        pageSize,
        typeName,
        status
    } = req.query;
    const condition = [
        isEmpty(typeName) ? " 1=1 and" : `type_name like '%${typeName}%' and `,
        isEmpty(status) ? " status=0 " : ` status=${status} `,
        `limit ${(pageNum-1)*pageSize},${pageSize}`
    ]
    const sqlStr = `select * from t_type where ${condition.join("")}`;
    const selectAllCount = `select count(*) as count from t_type ${isEmpty(status)?"where status=0":`where status=${status}`}`;
    console.log(sqlStr);
    let backData = {
        data: [], // 所查询到的数据
        pageNum, // 当前页码
        pageSize, // 每页显示的条数
        total: 0 // 总条数
    };
    query(selectAllCount).then(result => {
        backData.total = result[0].count;
        return query(sqlStr);
    }).then(result => {
        backData.data = result;
        res.send(json("success", 0, backData));
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("sql错误" + err));
    })
}